package newdecoupling.staffemp.controller;

import ch.qos.logback.classic.net.SimpleSocketServer;
import newdecoupling.staffemp.pojo.User;
import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcExample {

    @Test
    public void jdbcTest(){
        String url = "jdbc:mysql://localhost:3306/wod01"; // 替换成你的数据库名称
        String username = "root";  // 替换成你的数据库用户名
        String password = "123456"; // 替换成你的数据库密码
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        // 查询SQL语句
//        String sql = "SELECT id, username, password, name, age FROM staff_user WHERE username = 'daqiao' AND password = '123456'";
        String sql = "SELECT id, username, password, name, age FROM staff_user ";


        List<User> list = new ArrayList<>();

        try {
//

            connection = DriverManager.getConnection(url, username, password);
            statement = connection.createStatement();
            resultSet  = statement.executeQuery(sql);
            while (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setName(resultSet.getString("name"));
                user.setAge(resultSet.getInt("age"));
                // 将User对象添加到列表中
                list.add(user);
            }
            // 输出查询到的所有用户信息
            for (User user : list){
                System.out.println(user);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if(connection != null){
                    connection.close();
                }
                if(statement != null){
                    statement.close();;
                }
                if(resultSet != null){
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
